﻿using System;
using System.Web.UI.WebControls;

using System.Data;
using System.Data.SqlClient;
using System.Text;

namespace IFD2
{
    public partial class LineSituation : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Session["ACL"].ToString().IndexOf("IA1") < 0)
                {
                    Server.Transfer("unauthorized.aspx");
                }
                if (Session["FLT_DATE"] != null)
                    txtFltDate.Text = Convert.ToDateTime(Session["FLT_DATE"].ToString()).ToShortDateString();
                if (Session["ORI"] != null)
                    txtOriCity.Text = Session["ORI"].ToString();
                if (Session["DES"] != null)
                    txtDesCity.Text = Session["DES"].ToString();
                try
                {
                    lstCurrencies.SelectedValue = Session["DEFAULT_CURRENCY"].ToString();
                }
                catch (Exception ex)
                {
                    //Does nothing!
                }
            }
            
            btnTakeSample.Attributes.Add("onclick", "javascript:return confirm('Are you sure?');");
            btnDeleteSample.Attributes.Add("onclick", "javascript:return confirm('Are you sure?');");

            lblError.Text = "";
        }

        protected void btnDeleteSample_Click(object sender, EventArgs e)
        {
            int ret;
            SqlCommand cmd = new SqlCommand();
            SqlParameter para;
            cmd.CommandText = "bll_airline_delete_line_summary_sample";
            para = cmd.Parameters.AddWithValue("@airline", Session["AIRLINE"].ToString());
            para = cmd.Parameters.AddWithValue("@ori_city", txtOriCity.Text);
            para = cmd.Parameters.AddWithValue("@des_city", txtDesCity.Text);
            para = cmd.Parameters.AddWithValue("@date_focus", txtFltDate.Text);
            para = cmd.Parameters.AddWithValue("@week_on_week", radWeekOnWeek.Checked);
            para = cmd.Parameters.AddWithValue("@span", lstSpan.SelectedValue);
            para = cmd.Parameters.AddWithValue("@currency", lstCurrencies.SelectedValue);
            ret = TinyDAL.Exec(ref cmd);
            if (ret == 0)
            {
                lblError.Text = (string)base.GetLocalResourceObject("sqlDone.Text");//"Done.";
                litFlts.Text = "";
            }
            else if (ret == 1)
            {
                lblError.Text = (string)base.GetLocalResourceObject("sqlDeleteSample001.Text");//"Deleted nothing!";
                litFlts.Text = "";
            }
            else
                lblError.Text = (string)base.GetLocalResourceObject("sqlOthers.Text") + ret.ToString();
        }

        protected void btnTakeSample_Click(object sender, EventArgs e)
        {
            int ret;
            //try
            //{
            //    ret = int.Parse(lstSpan.SelectedValue);
            //}
            //catch (Exception ex)
            //{
            //    lblError.Text = "Invalid day span!";
            //    return;
            //}
            //if (ret<0 || ret>5)
            //{
            //    lblError.Text = "Too large span!";
            //    return;
            //}

            SqlCommand cmd = new SqlCommand();
            SqlParameter para;
            cmd.CommandText = "bll_airline_take_line_summary_sample";
            para = cmd.Parameters.AddWithValue("@airline", Session["AIRLINE"].ToString());
            para = cmd.Parameters.AddWithValue("@ori_city", txtOriCity.Text.ToUpper());
            para = cmd.Parameters.AddWithValue("@des_city", txtDesCity.Text.ToUpper());
            para = cmd.Parameters.AddWithValue("@date", txtFltDate.Text);
            para = cmd.Parameters.AddWithValue("@week_on_week", radWeekOnWeek.Checked);
            para = cmd.Parameters.AddWithValue("@span", lstSpan.SelectedValue);
            para = cmd.Parameters.AddWithValue("@currency", lstCurrencies.SelectedValue);
            ret = TinyDAL.Exec(ref cmd);
            litFlts.Text = "";
            switch (ret)
            {
                case 0:
                    Session["ORI"] = txtOriCity.Text.ToUpper();
                    Session["DES"] = txtDesCity.Text.ToUpper();
                    Session["FLT_DATE"] = txtFltDate.Text;
                    lblError.Text = (string)base.GetLocalResourceObject("sqlDone.Text");//"Done.";
                    break;
                case 1:
                    lblError.Text = (string)base.GetLocalResourceObject("sqlTakeSample001.Text");//"Too width span!";
                    break;
                case 2:
                    lblError.Text = (string)base.GetLocalResourceObject("sqlTakeSample002.Text");//"Flight not found!";
                    break;
                default:
                    lblError.Text = (string)base.GetLocalResourceObject("sqlOthers.Text") + ret.ToString();
                    break;
            }
        }

        struct sub_total
        {
            public int booked;
            public int tickets;
            //public string currency;
            public float income;
            public int open;
            public int pax_km;
            public int seat_km;
            public int flt_count;
        }
        protected void lbtnQuery_Click(object sender, EventArgs e)
        {
            try
            {
                DateTime.Parse(txtFltDate.Text);
            }
            catch
            {
                lblError.Text = "Invalid date format!";
                txtFltDate.Text = "";
                return;
            }
            Session["FLT_DATE"] = txtFltDate.Text;
            string airline = Session["AIRLINE"].ToString().TrimEnd();
            try
            {
                SqlCommand cmd = new SqlCommand();
                SqlParameter para;
                DataTable dt_ret = new DataTable();
                cmd.CommandText = "bll_airline_query_line_summary_sample";
                para = cmd.Parameters.AddWithValue("@airline", Session["AIRLINE"].ToString());
                para = cmd.Parameters.AddWithValue("@ori_city", txtOriCity.Text.ToUpper());
                para = cmd.Parameters.AddWithValue("@des_city", txtDesCity.Text.ToUpper());
                para = cmd.Parameters.AddWithValue("@date_focus", txtFltDate.Text);
                para = cmd.Parameters.AddWithValue("@week_on_week", radWeekOnWeek.Checked);
                para = cmd.Parameters.AddWithValue("@span", lstSpan.SelectedValue);
                para = cmd.Parameters.AddWithValue("@currency", lstCurrencies.SelectedValue);
                TinyDAL.Exec(ref cmd, ref dt_ret);
                if (dt_ret.Rows.Count == 0)
                {
                    lblError.Text = (string)base.GetLocalResourceObject("errNoData.Text");// "No sampling data!";
                    litFlts.Text = "";
                    return;
                }
                int i, day_diff, day_span, last_day_diff = -1;
                DateTime fltdate1, cur_date;
                StringBuilder buf = new StringBuilder();
                TimeSpan ts;
                string currency;

                txtOriCity.Text = dt_ret.Rows[0]["ori_city"].ToString();
                txtDesCity.Text = dt_ret.Rows[0]["des_city"].ToString();
                //fltdate1=Convert.ToDateTime(dt_ret.Rows[0]["date_focus"]);
                fltdate1 = Convert.ToDateTime(txtFltDate.Text);
                //txtFltDate.Text = fltdate1.ToShortDateString();
                //if (Convert.ToInt16(dt_ret.Rows[0]["week_on_week"]) == 0)
                //{
                //    radDayOnDay.Checked = true;
                //    radWeekOnWeek.Checked = false;
                //}
                //else
                //{
                //    radDayOnDay.Checked = false;
                //    radWeekOnWeek.Checked = true;
                //}
                //day_span= Convert.ToInt16(dt_ret.Rows[0]["span"]);
                day_span = Convert.ToInt16(lstSpan.SelectedValue);
                //lstSpan.SelectedValue = day_span.ToString();
                currency = lstCurrencies.SelectedValue;
                double percentage;
                sub_total[] summary = new sub_total[day_span * 2 + 1];

                buf.Append("<table style='min-width:700px;width:100%;'><thead><tr><th></th>");
                i = day_span * -1;
                //date_from = fltdate1.AddDays(i);
                //cur_date = date_from;
                do
                {
                    if (!radWeekOnWeek.Checked)
                        cur_date = fltdate1.AddDays(i);
                    else
                        cur_date = fltdate1.AddDays(i * 7);
                    buf.Append("<th style='text-align:center;'><b>" + cur_date.GetDateTimeFormats('M')[0].ToString() + "</b></th>");
                    i++;
                } while (i <= day_span);
                buf.Append("</tr></thead><tbody>");

                string last_flt_no = ((char)10).ToString();
                DateTime last_flt_date = Convert.ToDateTime("1950-1-1");
                bool is_first_date = true;

                //图表
                DataTable dtChart = new DataTable();
                DataRow drChart;
                dtChart.Columns.Add("FltDate", System.Type.GetType("System.DateTime"));
                dtChart.Columns.Add("Tickets", System.Type.GetType("System.Int16"));
                dtChart.Columns.Add("AvgPrice", System.Type.GetType("System.Single"));
                TableRow chartrow;
                TableCell chartcell;
                System.Web.UI.DataVisualization.Charting.Chart mychart;
                Random rd = new Random();
                foreach (DataRow row in dt_ret.Rows)
                {
                    ts = Convert.ToDateTime(row["flt_date"]).Subtract(fltdate1);
                    if (!radWeekOnWeek.Checked)
                        day_diff = ts.Days + day_span;
                    else
                        day_diff = ts.Days / 7 + day_span;
                    summary[day_diff].booked = summary[day_diff].booked + Convert.ToInt16(row["BOOKED"]);
                    summary[day_diff].tickets = summary[day_diff].tickets + Convert.ToInt16(row["TICKETS"]);
                    summary[day_diff].income = summary[day_diff].income + Convert.ToInt16(row["INCOME"]);
                    summary[day_diff].open = summary[day_diff].open + Convert.ToInt16(row["OPEN"]);
                    summary[day_diff].seat_km = summary[day_diff].seat_km + Convert.ToInt16(row["OPEN"]) * Convert.ToInt16(row["distance"]);
                    summary[day_diff].pax_km = summary[day_diff].pax_km + Convert.ToInt16(row["TICKETS"]) * Convert.ToInt16(row["distance"]);
                    summary[day_diff].flt_count = summary[day_diff].flt_count + 1;
                    if (last_flt_no != row["flt_no"].ToString().TrimEnd())
                    {
                        if (last_flt_no != ((char)10).ToString())
                        {
                            //图表
                            mychart = new System.Web.UI.DataVisualization.Charting.Chart();
                            mychart.DataSource = dtChart;
                            mychart.Width = 1024;
                            mychart.BackColor = System.Drawing.Color.LightSkyBlue;
                            mychart.Series.Add("Series1");
                            mychart.Series["Series1"].ChartType = System.Web.UI.DataVisualization.Charting.SeriesChartType.Line;//设置图表类型
                            mychart.Series["Series1"].XValueMember = "FltDate";//X轴数据成员列
                            mychart.Series["Series1"].YValueMembers = "Tickets";//Y轴数据成员列"Tickets,AvgPrice"
                            mychart.Series["Series1"].IsValueShownAsLabel = true;//显示坐标值
                            mychart.Series["Series1"].YAxisType = System.Web.UI.DataVisualization.Charting.AxisType.Primary;
                            mychart.Series["Series1"].XAxisType = System.Web.UI.DataVisualization.Charting.AxisType.Primary;
                            mychart.Series["Series1"].MarkerStyle = System.Web.UI.DataVisualization.Charting.MarkerStyle.Circle;
                            mychart.Series["Series1"].LegendText = "Tickets";
                            mychart.Series["Series1"].Color = System.Drawing.Color.Red;
                            mychart.ChartAreas.Add("ChartArea1");
                            //mychart.ChartAreas["ChartArea1"].AxisX.Title = "Flt. Date";//X轴标题
                            mychart.ChartAreas["ChartArea1"].AxisY.Title = "PAX";//Y轴标题
                            mychart.ChartAreas["ChartArea1"].AxisY2.Title = "Avg. Price - " + lstCurrencies.SelectedValue;//Y轴标题
                            mychart.ChartAreas["ChartArea1"].AxisX.MajorGrid.Enabled = false;//不显示竖着的分割线
                            mychart.ChartAreas["ChartArea1"].AxisY.MajorGrid.Enabled = false;//不显示竖着的分割线
                            mychart.ChartAreas["ChartArea1"].AxisY2.MajorGrid.Enabled = false;//不显示竖着的分割线
                            mychart.Series.Add("Series2");
                            mychart.Series["Series2"].ChartType = System.Web.UI.DataVisualization.Charting.SeriesChartType.Line;//设置图表类型
                            mychart.Series["Series2"].XValueMember = "FltDate";//X轴数据成员列
                            mychart.Series["Series2"].YValueMembers = "AvgPrice";//Y轴数据成员列"Tickets,AvgPrice"
                            mychart.Series["Series2"].IsValueShownAsLabel = true;//显示坐标值
                            mychart.Series["Series2"].YAxisType = System.Web.UI.DataVisualization.Charting.AxisType.Secondary;
                            mychart.Series["Series2"].MarkerStyle = System.Web.UI.DataVisualization.Charting.MarkerStyle.Diamond;
                            mychart.Series["Series2"].LegendText = "Avg. Price";
                            mychart.Series["Series2"].Color = System.Drawing.Color.Goldenrod;
                            mychart.DataBind();
                            chartrow = new TableRow();
                            chartcell = new TableCell();
                            chartcell.Text = Session["AIRLINE"].ToString() + last_flt_no;
                            chartrow.Cells.Add(chartcell);
                            chartcell = new TableCell();
                            chartcell.Controls.Add(mychart);
                            chartrow.Cells.Add(chartcell);
                            TabHolder.Rows.Add(chartrow);
                            dtChart.Rows.Clear();

                            buf.Append("</tr>");
                        }
                        last_flt_no = row["flt_no"].ToString().TrimEnd();

                        buf.Append("<tr style='text-align:center;'><td>" + airline + " " + last_flt_no + "<br/>");
                        buf.Append("<button class=\"btn btn-sm btn-default\" style=\"width:100px;\" type=\"button\" onclick=\"$('#ajaxContent').load('same_flt_class_bkd.ashx?flt_no=" + last_flt_no.Trim() + "&ori=" + txtOriCity.Text.Trim() + "&des=" + txtDesCity.Text.Trim() + "&date=" + fltdate1.ToShortDateString() + "&span=" + lstSpan.SelectedValue + "&weekonweek=");
                        if (radWeekOnWeek.Checked)
                            buf.Append("1");
                        else
                            buf.Append("0");
                        buf.Append("');$('#modPopup').modal('show');\">Classes...</button><br/>");
                        buf.Append("<button class=\"btn btn-sm btn-default\" style=\"width:100px;\" type=\"button\" onclick=\"$('#ajaxContent').load('same_flt_products.ashx?flt_no=" + last_flt_no.Trim() + "&ori=" + txtOriCity.Text.Trim() + "&des=" + txtDesCity.Text.Trim() + "&date=" + fltdate1.ToShortDateString() + "&span=" + lstSpan.SelectedValue + "&weekonweek=");
                        if (radWeekOnWeek.Checked)
                            buf.Append("1");
                        else
                            buf.Append("0");
                        buf.Append("');$('#modPopup').modal('show');\">Products...</button></td>");
                        //ts = Convert.ToDateTime(row["flt_date"]).Subtract(fltdate1);
                        if (!radWeekOnWeek.Checked)
                            day_diff = ts.Days + day_span;
                        else
                            day_diff = ts.Days / 7 + day_span;
                        for (i = 1; i <= day_diff; i++)
                            buf.Append("<td></td>");

                        last_flt_date = fltdate1;
                        last_day_diff = day_diff;
                        is_first_date = true;
                    }
                    if (!is_first_date)
                    {
                        //ts = Convert.ToDateTime(row["flt_date"]).Subtract(last_flt_date);
                        //if (!chkWeekOnWeek.Checked)
                        //    day_diff = ts.Days + day_span;
                        //else
                        //    day_diff = ts.Days / 7 + day_span;

                        for (i = 1; i < day_diff - last_day_diff; i++)
                            buf.Append("<td></td>");
                        last_day_diff = day_diff;
                    }
                    is_first_date = false;

                    //图表
                    drChart = dtChart.NewRow();
                    drChart["FltDate"] = Convert.ToDateTime(row["flt_date"]);
                    drChart["Tickets"] = Convert.ToInt16(row["TICKETS"]);
                    if (Convert.ToInt16(drChart["Tickets"]) == 0)
                        drChart["AvgPrice"] = 0;
                    else
                        drChart["AvgPrice"] = Convert.ToInt16(Convert.ToInt16(row["INCOME"]) / Convert.ToInt16(row["TICKETS"]));
                    dtChart.Rows.Add(drChart);

                    last_flt_date = Convert.ToDateTime(row["flt_date"]);
                    if (Convert.ToInt16(row["OPEN"]) > 0)
                    {
                        percentage = Convert.ToSingle(row["BOOKED"]) / Convert.ToInt16(row["OPEN"]);
                        percentage = Math.Round(percentage, 2);
                    }
                    else
                        percentage = 0;
                    if (percentage < 0.6) //0.6
                        buf.Append("<td style=\"background:#CECEFF\">");
                    else if (percentage < 0.95) //0.95
                        buf.Append("<td style=\"background:#52ba57\">");
                    else if (percentage < 1.0) //1.0
                        buf.Append("<td style=\"background:#ffff95\">");
                    else
                        buf.Append("<td style=\"background:OrangeRed\">");

                    buf.Append("<a href='FltInventory.aspx?flt_no=" + last_flt_no + "&flt_date=" + Convert.ToDateTime(row["flt_date"]).ToShortDateString() + "'>");
                    buf.Append(row["BOOKED"].ToString() + "<br/>" + row["TICKETS"].ToString() + "<BR/>" + currency);
                    if (Convert.ToInt16(row["TICKETS"]) > 0)
                        buf.Append((Convert.ToSingle(row["INCOME"]) / Convert.ToInt16(row["TICKETS"])).ToString() + "<br/>" + currency);
                    else
                        buf.Append("0<br/>" + currency);
                    if (Convert.ToInt16(row["OPEN"]) * Convert.ToInt16(row["distance"]) != 0)
                        buf.Append(Math.Round(Convert.ToSingle(row["INCOME"]) / Convert.ToInt16(row["OPEN"]) / Convert.ToInt16(row["distance"]), 4).ToString() + "<br/>" + currency);
                    else
                        buf.Append("0.0000<br/>" + currency);
                    if (Convert.ToInt16(row["TICKETS"]) * Convert.ToInt16(row["distance"]) != 0)
                        buf.Append(Math.Round(Convert.ToSingle(row["INCOME"]) / Convert.ToInt16(row["TICKETS"]) / Convert.ToInt16(row["distance"]), 4).ToString());
                    else
                        buf.Append("0.0000");

                    buf.Append("<BR/>" + (percentage * 100).ToString() + "%</a></td>");
                }
                //图表
                if (dt_ret.Rows.Count > 0)
                {
                    mychart = new System.Web.UI.DataVisualization.Charting.Chart();
                    mychart.DataSource = dtChart;
                    mychart.Width = 1024;
                    mychart.BackColor = System.Drawing.Color.LightSkyBlue;
                    mychart.Series.Add("Series1");
                    mychart.Series["Series1"].ChartType = System.Web.UI.DataVisualization.Charting.SeriesChartType.Line;//设置图表类型
                    mychart.Series["Series1"].XValueMember = "FltDate";//X轴数据成员列
                    mychart.Series["Series1"].YValueMembers = "Tickets";//Y轴数据成员列"Tickets,AvgPrice"
                    mychart.Series["Series1"].IsValueShownAsLabel = true;//显示坐标值
                    mychart.Series["Series1"].YAxisType = System.Web.UI.DataVisualization.Charting.AxisType.Primary;
                    mychart.Series["Series1"].XAxisType = System.Web.UI.DataVisualization.Charting.AxisType.Primary;
                    mychart.Series["Series1"].MarkerStyle = System.Web.UI.DataVisualization.Charting.MarkerStyle.Circle;
                    mychart.Series["Series1"].LegendText = "Tickets";
                    mychart.Series["Series1"].Color = System.Drawing.Color.Red;
                    mychart.ChartAreas.Add("ChartArea1");
                    //mychart.ChartAreas["ChartArea1"].AxisX.Title = "Flt. Date";//X轴标题
                    mychart.ChartAreas["ChartArea1"].AxisY.Title = "PAX";//Y轴标题
                    mychart.ChartAreas["ChartArea1"].AxisY2.Title = "Avg. Price - " + lstCurrencies.SelectedValue;//Y轴标题
                    mychart.ChartAreas["ChartArea1"].AxisX.MajorGrid.Enabled = false;//不显示竖着的分割线
                    mychart.ChartAreas["ChartArea1"].AxisY.MajorGrid.Enabled = false;//不显示竖着的分割线
                    mychart.ChartAreas["ChartArea1"].AxisY2.MajorGrid.Enabled = false;//不显示竖着的分割线
                    mychart.Series.Add("Series2");
                    mychart.Series["Series2"].ChartType = System.Web.UI.DataVisualization.Charting.SeriesChartType.Line;//设置图表类型
                    mychart.Series["Series2"].XValueMember = "FltDate";//X轴数据成员列
                    mychart.Series["Series2"].YValueMembers = "AvgPrice";//Y轴数据成员列"Tickets,AvgPrice"
                    mychart.Series["Series2"].IsValueShownAsLabel = true;//显示坐标值
                    mychart.Series["Series2"].YAxisType = System.Web.UI.DataVisualization.Charting.AxisType.Secondary;
                    mychart.Series["Series2"].MarkerStyle = System.Web.UI.DataVisualization.Charting.MarkerStyle.Diamond;
                    mychart.Series["Series2"].LegendText = "Avg. Price";
                    mychart.Series["Series2"].Color = System.Drawing.Color.Goldenrod;
                    mychart.DataBind();
                    chartrow = new TableRow();
                    chartcell = new TableCell();
                    chartcell.Text = Session["AIRLINE"].ToString() + last_flt_no;
                    chartrow.Cells.Add(chartcell);
                    chartcell = new TableCell();
                    chartcell.Controls.Add(mychart);
                    chartrow.Cells.Add(chartcell);
                    TabHolder.Rows.Add(chartrow);
                    dtChart.Rows.Clear();
                }

                buf.Append("</tr></tbody><tfoot><tr align='center'><td><b>TOTAL</b></td>");

                for (i = 0; i <= day_span * 2; i++)
                {
                    if (summary[i].flt_count > 0)
                    {
                        percentage = summary[i].booked * 1.0 / summary[i].open;
                        percentage = Math.Round(percentage, 2);
                        if (percentage < 0.6) //0.6
                            buf.Append("<td style=\"background:#CECEFF\">");
                        else if (percentage < 0.95) //0.95
                            buf.Append("<td style=\"background:#52ba57\">");
                        else if (percentage < 1.0) //1.0
                            buf.Append("<td style=\"background:#ffff95\">");
                        else
                            buf.Append("<td style=\"background:OrangeRed\">");

                        buf.Append(summary[i].booked.ToString() + "<br/>" + summary[i].tickets.ToString() + "<br/>");
                        if (summary[i].tickets > 0)
                            buf.Append(currency + (summary[i].income / summary[i].tickets).ToString() + "<br/>");
                        else
                            buf.Append(currency + "0<br/>");
                        if (summary[i].seat_km != 0)
                            buf.Append(currency + Math.Round(summary[i].income / summary[i].seat_km, 4).ToString() + "<br/>");
                        else
                            buf.Append(currency + "0.0000<br/>");
                        if (summary[i].pax_km != 0)
                            buf.Append(currency + Math.Round(summary[i].income / summary[i].pax_km, 4).ToString());
                        else
                            buf.Append(currency + "0.0000");
                        percentage = summary[i].booked * 1.0 / summary[i].open;
                        percentage = Math.Round(percentage, 2);
                        buf.Append("<br/>" + (percentage * 100).ToString() + "%");
                    }
                    else
                    {
                        buf.Append("<td></td>");
                    }
                }
                buf.Append("</tr></tfoot></table>");

                litFlts.Text = buf.ToString();

            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
            }
        }
    }
}